package com.akcome.apollo.config;

import java.util.LinkedHashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestAttributes;

/**
 * 实现自定义统一异常处理
 * @author wn
 *
 */
public class ApolloErrorAttributes extends DefaultErrorAttributes {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
			boolean includeStackTrace) {
		Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
		errorAttributes.put("code", 500);
		errorAttributes.put("msg", "系统异常");
		errorAttributes.put("data", null);
		requestAttributes.setAttribute("javax.servlet.error.status_code", HttpStatus.OK.value(), RequestAttributes.SCOPE_REQUEST);
		String path = getAttribute(requestAttributes, "javax.servlet.error.request_uri");
		logger.error("系统异常！！！请求地址：{}",path,getError(requestAttributes));
		return errorAttributes;
	}
	
	@SuppressWarnings("unchecked")
	private <T> T getAttribute(RequestAttributes requestAttributes, String name) {
		return (T) requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
	}

}
